﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MongoDB.Driver;
using MongoDB.Driver.Linq;


namespace SEOBlog.Domain
{
    public class Repository<T> : IRepository<T>
    {
        private readonly MongoDatabase _db;

        private readonly string _collectionName;

        protected Repository(string connectionString, string collectionName)
        {
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            var databaseName = MongoUrl.Create(connectionString).DatabaseName;
            
            _db = server.GetDatabase(databaseName);

            _collectionName = collectionName;
        }
        
        #region IRepository<T> Members

        public IQueryable<T> All()
        {
            var collection = _db.GetCollection(_collectionName);
            return collection.AsQueryable<T>();
        }

        public IQueryable<T> Where(Expression<Func<T, bool>> query)
        {
            var collection = _db.GetCollection(_collectionName);
            return collection.AsQueryable<T>().Where(query);
        }
        
        public bool Save(T entity)
        {
            var result = _db.GetCollection(_collectionName).Save(entity);
            return result.DocumentsAffected == 1;
        }

        public bool Insert(T entity)
        {
            var result = _db.GetCollection<T>(_collectionName).Insert(entity);
            return result.DocumentsAffected == 1;
        }

        public void Remove(T entity)
        {
        }

        #endregion
    }
}
